import React, { Component } from "react";
import { NavBar } from "antd-mobile";
import "./category.scss";
import Search from "../search/Search";
// myAxios
import myAxios from "../../utils/myAxios";
// 路由
import { withRouter } from "react-router-dom";
class Category extends Component {
  state = {
    categories: [], // 左侧的分类信息
    categories_list: [], // 右侧的商品信息
    selected_id: 0, // 选中一级标题的id
  };
  // 点击左侧导航事件
  leftClick = (e) => {
    console.log(e.target.getAttribute("data-index"));
    let selected_id = e.target.getAttribute("data-index");
    this.setState({
      selected_id: parseInt(selected_id),
      categories_list: this.state.categories[selected_id].children,
    });
    console.log(this.state.categories_list);
  };
  // 右侧点击商品
  singleClick = (e) => {
    // console.log(e.target.getAttribute("data-index"));
    var goods_key = e.target.getAttribute("data-index");
    this.props.history.push("/goodList?cid=" + goods_key);
  };
  // 设置分类菜单的数据
  setCategories = (res) => {
    this.setState({
      categories: res,
      categories_list: res[0].children,
    });
  };
  // 拿数据的一个函数
  getCategories = (params) => {
    myAxios
      .get("categories")
      .then((res) => {
        this.setCategories(res);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  // 把数据存储在本地
  setCategories = (res, is_storaged) => {
    let categories_cache = {};
    if (!is_storaged) {
      // 直接获取本地
      // categories_cache = JSON.parse(localStorage.getItem("categories"))
      // } else {
      categories_cache = {
        date: Date.now(), // 记录存储的时间
        categories: res,
      };
      localStorage.setItem("categories", JSON.stringify(categories_cache));
    }
    this.setState({
      categories: res,
      categories_list: res[0].children,
    });
  };
  componentDidMount() {
    // 判断本地有没有，如果本地有数据，就从本地取，并在本地设置数据的过期时间，减少请求数据的时间
    // 数据更新
    let localStorage_cache = localStorage.getItem("categories");
    // 确保请求回来的不为空对象bug
    if (localStorage_cache && JSON.parse(localStorage_cache).date) {
      // 有缓存，判断是否过期
      let current_time = Date.now();
      let before_time = JSON.parse(localStorage_cache).date;
      if (current_time - before_time > 1000 * 60 * 60) {
        // 一小时过期
        this.getCategories();
      } else {
        // 没过期，直接用本地的,已缓存
        var data = JSON.parse(localStorage_cache).categories;
        this.setCategories(data, true);
      }
    } else {
      // 第一次请求
      this.getCategories();
    }
  }
  render() {
    return (
      <div className="app-category">
        <div className="nav">
          <NavBar className="nav-con">商品分类</NavBar>
        </div>
        <div className="search">
          <Search></Search>
        </div>
        {/* 分类内容 */}
        <div className="category-content">
          {/* 给父元素写事件，利用事件冒泡 */}
          <div className="content-left" onClick={this.leftClick}>
            {this.state.categories.map((v, index) => {
              return (
                <div
                  key={v.cat_id}
                  data-index={index}
                  className={
                    this.state.selected_id === index
                      ? "active categories-title"
                      : "categories-title"
                  }
                >
                  {v.cat_name}
                </div>
              );
            })}
          </div>
          <div className="content-right">
            {this.state.categories_list.map((v) => {
              return (
                <div className="right-item" key={v.cat_id}>
                  <div className="right-item-title">
                    {"/"}
                    &nbsp;{v.cat_name}&nbsp;
                    {"/"}
                  </div>
                  {/* 点击商品进入商品列表页goodList ，给父元素绑定事件 */}
                  <div className="right-item-list">
                    {v.children &&
                      v.children.map((vv) => {
                        return (
                          <div
                            className="right-item-list-img-single"
                            key={vv.cat_id}
                          >
                            <div className="right-item-list-img">
                              <img
                               onClick={this.singleClick}
                                src={vv.cat_icon}
                                alt=""
                                data-index={vv.cat_id}
                              />
                            </div>
                            <div className="right-item-list-title">
                              {vv.cat_name}
                            </div>
                          </div>
                        );
                      })}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }
}
export default withRouter(Category);
